<template>
    <div>

        <a-collapse collapsible="header">
            <a-collapse-panel v-for="(a,ai) in sectors" :key="ai">
                <template #header>


                    <a-tooltip placement="topLeft">
                        <template #title>
                            {{ toNumber(a.value) }}
                        </template>
                         <i :class="['icon-'+(+a.value>0?'red':'green')]"></i>
                    </a-tooltip>

                    {{a.name}}


                </template>
                <a-spin :spinning="a.loading">
                    <div v-for="(b,bi) in a.news" :key="bi">
                        <b>
                            <span :class="{'font-red':isToday(b.Art_ShowTime)}">{{ b.Art_ShowTime }}</span>
                            {{ b.Art_MediaName }}
                        </b>
                        <p>
                            <a :href="b.Art_OriginUrl" target="_blank">{{ b.Art_Title }}</a>
                        </p>

                    </div>
                </a-spin>

                <template #extra><SyncOutlined @click="handleSync(a.code)"/></template>
            </a-collapse-panel>
        </a-collapse>

    </div>
</template>

<script>
import { findSectorWithNews,getNews } from "@/api/sector";
import { findTuyere } from "@/api/tuyere";
import {Collapse,CollapsePanel,Spin,Tooltip} from "ant-design-vue";
import { SyncOutlined } from '@ant-design/icons-vue';
import dayjs from "dayjs";
import isToday from "dayjs/plugin/isToday";
dayjs.extend(isToday)
import {sortObjectByValueDesc} from "@/views/tuyere/index.vue"
import { NumberZh } from "number-zh";
const numberZh = new NumberZh();

export default {
    components: {
        ACollapse: Collapse,
        ACollapsePanel: CollapsePanel,
        SyncOutlined,
        ASpin: Spin,
        ATooltip:Tooltip

    },
    data(){
        return {
            sectors: []
        }

    },

    mounted(){


        findSectorWithNews().then(async res=>{


            // 使用while循环实现优雅的重试机制
            let res1 = null;
            let retries = 0;
            const maxRetries = 10; // 最大重试次数
            const retryDelay = 100; // 重试延迟(毫秒)

            while (retries < maxRetries) {
                let prevDate = dayjs().subtract(retries, 'day').format('YYYY-MM-DD');
                res1 = await findTuyere({
                    date: prevDate
                });

                if (res1.data && res1.data.chart) {
                    // 成功获取到有效数据，退出循环
                    break;
                }

                retries++;
                if (retries < maxRetries) {
                    console.log(`获取数据失败，${retries}秒后重试...`);
                    await new Promise(resolve => setTimeout(resolve, retryDelay));
                }
            }

            // 最终检查，如果仍未获取到数据则抛出错误或进行处理
            if (!res1.data || !res1.data.chart) {
                console.error(`超过最大重试次数(${maxRetries})，未能获取有效数据`);
                return;
                // 可以选择抛出错误或设置默认值
                // throw new Error('Failed to fetch valid data after multiple attempts');
            }



            let sorted = sortObjectByValueDesc(res1.data.chart);
            let rows = [];

            for(let a in sorted){

                let row = res.data.rows.find(b=>b.code === a);

                row.value = sorted[a];
                row.loading = false;

                if (row.news){
                    row.news = JSON.parse(row.news);
                } else {
                    row.news = [];
                }

                rows.push(row);


            }


            this.sectors = rows;


        })
    },
    methods: {
        toNumber(n){
            return numberZh.numberToZh(n)
        },
        isToday(date){
            return dayjs(date).isToday()
        },
        handleSync(code){


            let row = this.sectors.find(a=> a.code === code);
            row.loading = true;

            this.$nextTick(()=>{
                getNews(code).then(res=>{
                    row.news = res.data;
                    row.loading = false;
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.icon-red{
    background-color: red;
    width: 10px;
    height: 10px;
    display: inline-block;
}
.icon-green{
    background-color: green;
    width: 10px;
    height: 10px;
    display: inline-block;
}
</style>
